package com.filldream.fastboot.core.manager;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.img.ImgUtil;
import com.filldream.fastboot.base.response.common.CaptchaDTO;
import com.filldream.fastboot.common.entity.B;
import com.filldream.fastboot.common.util.RandomUtil;
import com.filldream.fastboot.core.cache.CacheMap;
import com.filldream.fastboot.core.cache.CacheObj;
import com.filldream.fastboot.core.cache.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import java.awt.*;
import java.util.Map;

@Slf4j
public class CheckCodeUtil {

    /*图片验证码宽度*/
    private static final int width = 100;

    /*图片验证码高度*/
    private static final int height = 38;

    /*干扰线数量*/
    private static final int lineNum = 12;

    /*图片验证码长度4位*/
    private static final int length = 4;

    /*图片验证码默认过期时间*/
    private static final int expireIn = 60;

    private static final int codeCount = 4;

    private static final int circleCount = 4;

    /**
     * 创建一个图形验证码
     * @return
     */
    public static CaptchaDTO createVerifyCode() {

        CaptchaDTO result = new CaptchaDTO();

        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height, codeCount, circleCount);

        //验证码内容
        Map<String, String> map = RandomUtil.randMath(0, 20);
        String q = map.get("ex");
        //验证码答案
        String a = map.get("result");;

        Image image = captcha.createImage(q + "=");

        String imageBase64 = ImgUtil.toBase64(image,"png");

        String key = RandomUtil.randAlphaNumString(64).toUpperCase();

        result.setAnswer( a );
        result.setCode(q);
        result.setImageBase64(imageBase64);
        result.setKey(key);

        CacheUtil.cacheObj(CacheMap.CAPTCHA_CODE.getKeyName(key),result,120);

        return result.init();
    }

    /**
     * 校验图形验证码
     * @param captchaCode   验证码
     * @return
     */
    public static B checkCaptcha(String captchaCode,String key){
        if(!StringUtils.isNotBlank(captchaCode)){ return B.fail("验证码不能为空").put("need",true); }
        CacheObj<CaptchaDTO> cache = CacheUtil.getCache(CacheMap.CAPTCHA_CODE, CaptchaDTO.class, key);
        String cacheKey = cache.getCacheKey();
        CaptchaDTO captchaDTO = cache.getData();
        if( ObjectUtils.isEmpty( captchaDTO ) ){
            return B.fail("验证码已失效").put("need",true);
        }
        if( !key.equals(captchaDTO.getKey()) ){
            return B.fail("验证码错误.").put("need",true);
        }
        if( !captchaCode.equals(captchaDTO.getAnswer()) ){
            return B.fail("验证码错误").put("need",true);
        }
        CacheUtil.delKey(cacheKey);
        return B.success().put("need",true);
    }


}
